package com.leshua.channel.mpos.intercepter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.yeahka.commons.utils.NetUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by Administrator on 2017/9/11.
 */
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        long startTime = System.currentTimeMillis();
        String date = new SimpleDateFormat("yyMMddHHmmss").format(new Date());
        int random = (int) (Math.random() * 1000);
        String id = date + random;
        MDC.put("id", id);
        MDC.put("startTime", String.valueOf(startTime));

        //打印请求内容
        StringBuilder sb = new StringBuilder(1000);
        try {
            String method = request.getMethod();
            sb.append("\n");
            sb.append("请求内容：\n");
            if ("GET".equals(method)) {
                sb.append("reqParams : " + JSON.toJSONString(request.getParameterMap()) + "\n");
            } else {
                StringBuilder responseStrBuilder = new StringBuilder();
                BufferedReader streamReader = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
                String inputStr;
                while ((inputStr = streamReader.readLine()) != null)
                    responseStrBuilder.append(inputStr);
                sb.append("reqParams : " + responseStrBuilder.toString() + "\n");
            }
            if (handler instanceof HandlerMethod) {
                HandlerMethod h = (HandlerMethod) handler;
                sb.append("ReqMethod : ").append(method).append("\n");
                sb.append("Controller: ").append(h.getBean().getClass().getName()).append("\n");
                sb.append("Method    : ").append(h.getMethod().getName()).append("\n");
            }
        } catch (Exception e) {
            log.error("记录日志失败" + e.getMessage());
        }

        String username = "";
        log.info("访问用户的真实Ip为" + NetUtil.getRealIP(request) + "登录用户为[" + username + "]请求地址为： -->" + request.getRequestURI() + "参数为：     --> " + sb.toString());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception
            ex) throws Exception {

        long startTime = Long.parseLong((String) MDC.get("startTime"));

        log.info("请求地址为： -->" + request.getRequestURI() + "  消耗: -->" + (System.currentTimeMillis() - startTime) / 1000d);

        MDC.clear();
    }
}
